package com.wkbb.sports.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wkbb.common.base.BaseServiceImpl;
import com.wkbb.common.dto.ResultDTO;
import com.wkbb.sports.dto.MetaverseClockInDto;
import com.wkbb.sports.mapper.MetaverseActivityMapper;
import com.wkbb.sports.model.*;
import com.wkbb.sports.service.MetaverseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class MetaverseServiceImpl extends BaseServiceImpl<MetaverseActivityLocation> implements MetaverseService {

    @Autowired
    private MetaverseActivityMapper metaverseActivityMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public int putMetaverseActivityLocationList(List<MetaverseActivityLocation> list) throws Exception {
        return metaverseActivityMapper.insertMetaverseActivityLocationList(list);
    }

    @Override
    @Transactional(readOnly = true)
    public List<MetaverseActivityLocation> getMetaverseActivityLocationList() {
        return metaverseActivityMapper.getMetaverseActivityLocationList();
    }

    @Override
    public ResultDTO<MetaverseID> putMetaverseID(MetaverseID data) {
        MetaverseID old = metaverseActivityMapper.getMetaverseIDByUserId(data.getUserId());
        if (old != null) return ResultDTO.errorResult("不能重复领取");
        data.setUniqueId(metaverseId());
        metaverseActivityMapper.insertMetaverseID(data);
        return ResultDTO.successResult(data);
    }

    @Override
    @Transactional(readOnly = true)
    public MetaverseID getMetaverseIDByUserId(Long userId) {
        return metaverseActivityMapper.getMetaverseIDByUserId(userId);
    }

    @Override
    public ResultDTO<Boolean> clockIn(MetaverseClockIn data) throws Exception {
        if (data.getId() == null){
            MetaverseActivityLocation activityLocation = metaverseActivityMapper.getMetaverseActivityLocation(data.getActivityLocationId());
            if (activityLocation == null)
                return ResultDTO.errorResult("活动地点不存在，打卡失败");
            MetaverseClockIn old = metaverseActivityMapper.getClockIn(data);
            if (old != null) return ResultDTO.errorResult("当前地点已经打过卡啦");
            metaverseActivityMapper.insertMetaverseClockIn(data);
        }else{
            metaverseActivityMapper.updateMetaverseClockIn(data);
        }
        return ResultDTO.successResult(true);
    }

    @Override
    @Transactional(readOnly = true)
    public PageInfo<MetaverseClockInDto> getClockInListByPage(Map<String, Object> params, int pageNo, int pageSize) {
        Page<MetaverseClockInDto> page = PageHelper.startPage(pageNo, pageSize,true);
        PageInfo<MetaverseClockInDto> pageInfo = new PageInfo(metaverseActivityMapper.getClockInList(params));
        pageInfo.setTotal(page.getTotal());
        return pageInfo;
    }

    /**
     * 获取年的后两位加上一年多少天+当前小时数作为前缀
     * @return
     */
    public String getMetaverseIdPrefix() {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        // $后的0表示，位数不够用0补齐，如果没有这个0（如%1$nd）就以空格补齐，0后面的n表示总长度，总长度可以可以是大于9例如（%1$010d），d表示将var按十进制转字符串，长度不够的话用0或空格补齐。
        String monthFormat = String.format("%1$02d", month+1);
        String dayFormat = String.format("%1$02d", day);
        String hourFormat = String.format("%1$02d", hour);
        return year + monthFormat + dayFormat + hourFormat;
    }

    /**
     * 生成元宇宙ID
     */
    public String metaverseId() {
        String prefix = getMetaverseIdPrefix();
        String key = "METAVERSE_ID" + prefix;
        String metaverseId = null;
        try {
            Long increment = redisTemplate.opsForValue().increment(key,1);
            //往前补6位
            metaverseId=prefix+String.format("%1$06d",increment);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return metaverseId;
    }
}
